package com.ktwlsoft.archivemanage.domain.business.businessService.export;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.ktwlsoft.archivemanage.domain.business.businessService.businessInspect.BusinessInspectService;
import com.ktwlsoft.archivemanage.domain.business.businessService.guiBusiness.BusinessGuidanceService;
import com.ktwlsoft.archivemanage.domain.business.businessService.guiBusiness.GuiGuidanceMendListService;
import com.ktwlsoft.archivemanage.domain.business.businessService.pdf.PDFService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.AccountRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.ImgsService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.OperationRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.businessInspect.BusinessInspectRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.guiBusiness.GuiGuidanceMendListRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.mend.MendListRepositoryService;
import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.entity.Imgs;
import com.ktwlsoft.archivemanage.domain.dao.entity.OperationLog;
import com.ktwlsoft.archivemanage.domain.dao.entity.businessInspect.BusinessInspect;
import com.ktwlsoft.archivemanage.domain.dao.entity.guiBusiness.GuiBusinessGuidance;
import com.ktwlsoft.archivemanage.domain.dao.entity.mend.MendList;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.businessInspect.BusinessInspectFindPageRequest;
import com.ktwlsoft.archivemanage.payload.excel.BusinessGuidanceExcel;
import com.ktwlsoft.archivemanage.payload.excel.GuiBusinessGuidanceExcel;
import com.ktwlsoft.archivemanage.payload.excel.GuidanceMendListExcel;
import com.ktwlsoft.archivemanage.payload.excel.MendListExcel;
import com.ktwlsoft.archivemanage.payload.guiBusiness.GuiBusinessPageRequest;
import com.ktwlsoft.archivemanage.payload.guiBusiness.GuidanceMendListBatchExportRequest;
import com.ktwlsoft.archivemanage.payload.guiBusiness.MendListGetDetailsResult;
import com.ktwlsoft.archivemanage.payload.guiBusiness.MendListItemResult;
import com.ktwlsoft.archivemanage.payload.mendList.*;
import com.ktwlsoft.archivemanage.payload.operationLog.SaveLogRequest;
import com.ktwlsoft.archivemanage.service.img.FileStorageService;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import com.ktwlsoft.archivemanage.service.utils.DateUtils;
import com.ktwlsoft.archivemanage.service.utils.ExcelUtils;
import com.ktwlsoft.archivemanage.service.utils.ZipUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 导出
 *
 * @author zhuhe on 2019/11/12 11:06
 * @version 1.0
 */
@Component
public class ExportService {

    /**整改单*/
    private final MendListRepositoryService mendListRepositoryService;

    /**业务指导整改*/
    private final GuiGuidanceMendListRepositoryService guiGuidanceMendListRepositoryService;

    /**业务检查*/
    private final BusinessInspectRepositoryService repositoryService;

    /**业务检查*/
    private final BusinessInspectService businessInspectService;

    private final FileStorageService fileStorageService;

    private final PDFService pdfService;

    private final AccountRepositoryService accountRepositoryService;

    /**指导整改*/
    private final GuiGuidanceMendListService guidanceMendListService;

    /**业务指导*/
    private final BusinessGuidanceService businessGuidanceService;

    /**图片*/
    private final ImgsService imgsService;

    public ExportService(MendListRepositoryService mendListRepositoryService, GuiGuidanceMendListRepositoryService guiGuidanceMendListRepositoryService, BusinessInspectRepositoryService repositoryService, BusinessInspectService businessInspectService, FileStorageService fileStorageService, PDFService pdfService, AccountRepositoryService accountRepositoryService, GuiGuidanceMendListService guidanceMendListService, BusinessGuidanceService businessGuidanceService, ImgsService imgsService) {
        this.mendListRepositoryService = mendListRepositoryService;
        this.guiGuidanceMendListRepositoryService = guiGuidanceMendListRepositoryService;
        this.repositoryService = repositoryService;
        this.businessInspectService = businessInspectService;
        this.fileStorageService = fileStorageService;
        this.pdfService = pdfService;
        this.accountRepositoryService = accountRepositoryService;
        this.guidanceMendListService = guidanceMendListService;
        this.businessGuidanceService = businessGuidanceService;
        this.imgsService = imgsService;
    }

    /**
     * 整改单批量导出 on 2019/11/12 11:08
     *
     * @param request request
     * @param response response
     */
    public void mendListBatchExport(MendListPageRequest request, HttpServletResponse response){
        if(request.getPn() == null){
            request.setPn(1);
        }
        if(request.getPageSize() == null){
            request.setPageSize(30);
        }
        List<MendListExcel> mendLists = Lists.newArrayList();
        PageInfo<MendList> pageInfo = mendListRepositoryService.findMendListPage(request,"wx");
        if(pageInfo.getList() != null && pageInfo.getList().size() > 0){
            for(MendList mendList:pageInfo.getList()){
                MendListExcel mendListExcel = new MendListExcel();
                BeanUtils.copyProperties(mendList,mendListExcel);
                mendLists.add(mendListExcel);
            }
            ExcelUtils.generateMendListExcelFile(response,mendLists);
        }
    }

    /**
     * 检查整改整份导出 on 2019/11/12 11:02
     *
     * @param id id
     * @param request request
     */
    public ResponseEntity<?> mendListWholeExport(Long id,Long userId, HttpServletRequest request){
        MendListResponse response = mendListRepositoryService.findDetail(id);
        if(response == null){
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在"));
        }
        int i = 1;
        if(response.getMendSubjectList() != null){
            for(MendSubjectResponse subjectResponse:response.getMendSubjectList()){
                if(subjectResponse.getImgs() != null){
                    i += subjectResponse.getImgs().size();
                }
                if(subjectResponse.getMendOptionResponseList() != null && subjectResponse.getMendOptionResponseList().size() > 0) {
                    for (MendOptionResponse optionResponse : subjectResponse.getMendOptionResponseList()) {
                        if (optionResponse.getImgs() != null && optionResponse.getImgs().size() > 0) {
                            i += optionResponse.getImgs().size();
                        }
                    }
                }
            }
        }
        File[] files = 	new File[i];
        //pdf
        try {
            files[0] = new File(pdfService.createPDF(1,id));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("系统找不到文件路径"));
        }
        //zip路径
        String zipPash = fileStorageService.getStrPath(files[0].getPath());
        zipPash = zipPash.substring(0,zipPash.lastIndexOf(File.separator)) + File.separator + response.getArchiveUnit() + ".zip";
        //文件
        if(response.getMendSubjectList() != null){
            List<Imgs> imgss = Lists.newArrayList();
            for(MendSubjectResponse subjectResponse:response.getMendSubjectList()){
                if(subjectResponse.getImgs() != null && subjectResponse.getImgs().size() > 0){
                    imgss.addAll(subjectResponse.getImgs());
                }
                //选项图片
                if(subjectResponse.getMendOptionResponseList() != null && subjectResponse.getMendOptionResponseList().size() > 0) {
                    for (MendOptionResponse optionResponse : subjectResponse.getMendOptionResponseList()) {
                        if (optionResponse.getImgs() != null && optionResponse.getImgs().size() > 0) {
                            imgss.addAll(optionResponse.getImgs());
                        }
                    }
                }
            }
            for(int i1 = 0;i1 < imgss.size();i1++){
                files[i1 + 1] = new File(fileStorageService.getStrPath(imgss.get(i1).getUrl()));
            }
        }
        Resource resource = null;
        try {
            //生成zip并获取
            resource = new UrlResource(new File(ZipUtils.zipFiles(files,zipPash,null)).toURI());
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("系统找不到文件路径"));
        }
        if (!resource.exists()) {
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("生成zip失败"));
        }
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            System.out.println("Could not determine file type.");
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        //名字转换
        String[] strArr = resource.getFilename().split("\\.");
        String fileNamePrefix = strArr[0];
        String fileNameSuffix = strArr[1];
        String finalFileName = null;
        try {
            finalFileName = URLEncoder.encode(fileNamePrefix,"UTF-8")+"."+fileNameSuffix;
        }catch (UnsupportedEncodingException e){
            System.out.println("文件名字转换异常");
            System.out.println(e.getMessage());
        }
        OperationRepositoryService.saveLog(new SaveLogRequest(
                OperationLog.OperationType.EXPORT,
                "导出检查整改,检查单号:" + response.getGuidNum(),
                "检查整改",
                OperationLog.BusinessType.BUSINESS
        ),accountRepositoryService.getById(userId));
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + response.getGuidNum() + "_" + finalFileName + "\"").body(resource);
    }

    /**
     * 自查复查检查整改整份导出 on 2019/11/12 11:02
     *
     * @param id id
     * @param request request
     */
    public ResponseEntity<?> selfOrRepeatMendListWholeExport(Long id,Long userId, HttpServletRequest request){
        MendListResponse response = mendListRepositoryService.findDetail(id);
        if(response == null){
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在"));
        }
        int i = 1;
        if(response.getMendSubjectList() != null){
            for(MendSubjectResponse subjectResponse:response.getMendSubjectList()){
                if(subjectResponse.getImgs() != null){
                    i += subjectResponse.getImgs().size();
                }
                if(subjectResponse.getMendOptionResponseList() != null && subjectResponse.getMendOptionResponseList().size() > 0) {
                    for (MendOptionResponse optionResponse : subjectResponse.getMendOptionResponseList()) {
                        if (optionResponse.getImgs() != null && optionResponse.getImgs().size() > 0) {
                            i += optionResponse.getImgs().size();
                        }
                    }
                }
            }
        }
        File[] files = 	new File[i];
        //pdf
        try {
            files[0] = new File(pdfService.selfOrRepeatCreatePDF(1,id));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("系统找不到文件路径"));
        }
        //zip路径
        String zipPash = fileStorageService.getStrPath(files[0].getPath());
        zipPash = zipPash.substring(0,zipPash.lastIndexOf(File.separator)) + File.separator + response.getArchiveUnit() + ".zip";
        //文件
        if(response.getMendSubjectList() != null){
            List<Imgs> imgss = Lists.newArrayList();
            for(MendSubjectResponse subjectResponse:response.getMendSubjectList()){
                if(subjectResponse.getImgs() != null && subjectResponse.getImgs().size() > 0){
                    imgss.addAll(subjectResponse.getImgs());
                }
                //选项图片
                if(subjectResponse.getMendOptionResponseList() != null && subjectResponse.getMendOptionResponseList().size() > 0) {
                    for (MendOptionResponse optionResponse : subjectResponse.getMendOptionResponseList()) {
                        if (optionResponse.getImgs() != null && optionResponse.getImgs().size() > 0) {
                            imgss.addAll(optionResponse.getImgs());
                        }
                    }
                }
            }
            for(int i1 = 0;i1 < imgss.size();i1++){
                files[i1 + 1] = new File(fileStorageService.getStrPath(imgss.get(i1).getUrl()));
            }
        }
        Resource resource = null;
        try {
            //生成zip并获取
            resource = new UrlResource(new File(ZipUtils.zipFiles(files,zipPash,null)).toURI());
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("系统找不到文件路径"));
        }
        if (!resource.exists()) {
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("生成zip失败"));
        }
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            System.out.println("Could not determine file type.");
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        //名字转换
        String[] strArr = resource.getFilename().split("\\.");
        String fileNamePrefix = strArr[0];
        String fileNameSuffix = strArr[1];
        String finalFileName = null;
        try {
            finalFileName = URLEncoder.encode(fileNamePrefix,"UTF-8")+"."+fileNameSuffix;
        }catch (UnsupportedEncodingException e){
            System.out.println("文件名字转换异常");
            System.out.println(e.getMessage());
        }
        OperationRepositoryService.saveLog(new SaveLogRequest(
                OperationLog.OperationType.EXPORT,
                "导出检查整改,检查单号:" + response.getGuidNum(),
                "检查整改",
                OperationLog.BusinessType.BUSINESS
        ),accountRepositoryService.getById(userId));
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + response.getGuidNum() + "_" + finalFileName + "\"").body(resource);
    }

    /**
     * 检查整改文件导出 on 2019/11/12 11:02
     *
     * @param id id
     * @param request request
     */
    public ResponseEntity<?> mendListFileExport(Long id,Long userId, HttpServletRequest request){
        MendListResponse response = mendListRepositoryService.findDetail(id);
        if(response == null){
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在"));
        }
        int i = 0;
        if(response.getMendSubjectList() != null){
            for(MendSubjectResponse subjectResponse:response.getMendSubjectList()){
                if(subjectResponse.getImgs() != null){
                    i += subjectResponse.getImgs().size();
                }
                if(subjectResponse.getMendOptionResponseList() != null && subjectResponse.getMendOptionResponseList().size() > 0) {
                    for (MendOptionResponse optionResponse : subjectResponse.getMendOptionResponseList()) {
                        if (optionResponse.getImgs() != null && optionResponse.getImgs().size() > 0) {
                            i += optionResponse.getImgs().size();
                        }
                    }
                }
            }
        }
        if(i <= 0){
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("没有文件可以下载"));
        }
        File[] files = 	new File[i];
        //文件
        if(response.getMendSubjectList() != null){
            List<Imgs> list = Lists.newArrayList();
            for(MendSubjectResponse subjectResponse:response.getMendSubjectList()){
                if(subjectResponse.getImgs() != null && subjectResponse.getImgs().size() > 0){
                    for(int i1 = 0;i1 < subjectResponse.getImgs().size();i1++){
                        list.add(subjectResponse.getImgs().get(i1));
                    }
                }
                //选项图片
                if(subjectResponse.getMendOptionResponseList() != null && subjectResponse.getMendOptionResponseList().size() > 0) {
                    for (MendOptionResponse optionResponse : subjectResponse.getMendOptionResponseList()) {
                        if (optionResponse.getImgs() != null && optionResponse.getImgs().size() > 0) {
                            list.addAll(optionResponse.getImgs());
                        }
                    }
                }
            }
            if(list.size() > 0){
                for(int i1 = 0;i1 < list.size();i1++){
                    files[i1] = new File(fileStorageService.getStrPath(list.get(i1).getUrl()));
                }
            }
        }
        //zip路径
        String zipPash = fileStorageService.getStrPath(files[0].getPath());
        zipPash = zipPash.substring(0,zipPash.lastIndexOf(File.separator)) + File.separator + response.getArchiveUnit() + ".zip";
        Resource resource = null;
        try {
            //生成zip并获取
            resource = new UrlResource(new File(ZipUtils.zipFiles(files,zipPash,null)).toURI());
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("系统找不到文件路径"));
        }
        if (!resource.exists()) {
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("生成zip失败"));
        }
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            System.out.println("Could not determine file type.");
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        //名字转换
        String[] strArr = resource.getFilename().split("\\.");
        String fileNamePrefix = strArr[0];
        String fileNameSuffix = strArr[1];
        String finalFileName = null;
        try {
            finalFileName = URLEncoder.encode(fileNamePrefix,"UTF-8")+"."+fileNameSuffix;
        }catch (UnsupportedEncodingException e){
            System.out.println("文件名字转换异常");
            System.out.println(e.getMessage());
        }
        OperationRepositoryService.saveLog(new SaveLogRequest(
                OperationLog.OperationType.EXPORT,
                "导出检查整改,检查单号:" + response.getGuidNum(),
                "检查整改",
                OperationLog.BusinessType.BUSINESS
        ),accountRepositoryService.getById(userId));
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + finalFileName + "\"").body(resource);
    }

    /**
     * 业务检查批量导出 on 2019/11/13 14:23
     *
     * @param request request
     * @param response response
     */
    public void businessGuidanceBatchExport(BusinessInspectFindPageRequest request, HttpServletResponse response){
        JSONObject object = new JSONObject();
        object.put("temId",request.getTemId() != null?request.getTemId():null);
        object.put("instructorId",request.getInstructorId() != null?request.getInstructorId():null);
        object.put("guidanceTimeStart", request.getGuidanceTimeStart() != null? DateUtils.dayMinTime(request.getGuidanceTimeStart()):null);
        object.put("guidanceTimeEnd",request.getGuidanceTimeEnd() != null?DateUtils.dayMaxTime(request.getGuidanceTimeEnd()):null);
        object.put("markStart",request.getMarkStart() != null?request.getMarkStart():null);
        object.put("markEnd",request.getMarkEnd() != null?request.getMarkEnd():null);
        object.put("state",request.getState() != null?request.getState():null);
        object.put("keyWords",request.getKeyWords() != null?request.getKeyWords():null);
        object.put("inspectType", request.getInspectType() != null ? request.getInspectType(): "default");
        if(request.getPn() == null){
            request.setPn(1);
        }
        if(request.getPageSize() == null){
            request.setPageSize(30);
        }
        List<BusinessGuidanceExcel> excelList = Lists.newArrayList();
        PageInfo<BusinessInspect> pageInfo = repositoryService.findPage(request.getPn(),request.getPageSize(),object);
        if(pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            for(BusinessInspect businessInspect :pageInfo.getList()){
                BusinessGuidanceExcel businessGuidanceExcel = new BusinessGuidanceExcel();
                BeanUtils.copyProperties(businessInspect,businessGuidanceExcel);
                businessGuidanceExcel.setMark(businessInspect.getMark() + "分/" + businessInspect.getFullMark() + "分");
                if(businessInspect.getState().equals(BusinessInspect.state.COMPLETE)){
                    businessGuidanceExcel.setState("完结");
                }else if(businessInspect.getState().equals(BusinessInspect.state.STAGE)){
                    businessGuidanceExcel.setState("暂存");
                }
                excelList.add(businessGuidanceExcel);
            }
            ExcelUtils.generateBusinessGuidanceExcelFile(response, excelList);
        }
    }

    /**
     * 业务检查整份导出 on 2019/11/12 11:02
     *
     * @param id id
     * @param request request
     */
    public ResponseEntity<?> businessGuidanceWholeExport(Long id,Long userId, HttpServletRequest request){
        Result result = businessInspectService.getById(id);
        if(result.getData() == null){
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在"));
        }
        JSONObject response = JSONObject.parseObject(JSON.toJSONString(result.getData(), SerializerFeature.WriteMapNullValue));
        int i = 1;
        if(response.get("instructorSignImg") != null){
            i += 1;
        }
        if(response.get("unitSignImg") != null){
            i += 1;
        }
        if(response.get("subjects") != null){
            List<JSONObject> list = JSONObject.toJavaObject(response.getJSONArray("subjects"),List.class);
            for(JSONObject object:list){
                if(object.get("imgsList") != null){
                    List imgss = JSONObject.toJavaObject(object.getJSONArray("imgsList"),List.class);
                    if(imgss != null) {
                        i += imgss.size();
                    }
                }
                if(object.get("itemList") != null){
                    List<JSONObject> itemList = JSONObject.toJavaObject(object.getJSONArray("itemList"),List.class);
                    for(JSONObject jsonObject:itemList){
                        if(jsonObject.get("imgsList") != null){
                            List imgs = JSONObject.toJavaObject(jsonObject.getJSONArray("imgsList"),List.class);
                            if(imgs != null) {
                                i += imgs.size();
                            }
                        }
                    }
                }
            }
        }
        File[] files = 	new File[i];
        //pdf
        try {
            files[0] = new File(pdfService.createPDF(2,id));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("系统找不到文件路径"));
        }
        //文件
        int x = 1;
        if(response.get("instructorSignImg") != null){
            List<JSONObject> object = JSONObject.toJavaObject(response.getJSONArray("instructorSignImg"),List.class);
            if(object != null && object.size() > 0 && object.get(0).get("url") != null) {
                files[1] = new File(object.get(0).getString("url"));
                x += 1;
            }
        }
        if(response.get("unitSignImg") != null){
            List<JSONObject> object = JSONObject.toJavaObject(response.getJSONArray("unitSignImg"),List.class);
            if(object != null && object.size() > 0 && object.get(0).get("url") != null) {
                files[2] = new File(object.get(0).getString("url"));
                x += 1;
            }
        }
        if(response.get("subjects") != null){
            List<JSONObject> list = JSONObject.toJavaObject(response.getJSONArray("subjects"),List.class);
            List<JSONObject> imgss = Lists.newArrayList();
            for(JSONObject object:list){
                if(object.get("imgsList") != null){
                    imgss.addAll(JSONObject.toJavaObject(object.getJSONArray("imgsList"),List.class));
                }
                //选项图片
                if(object.get("itemList") != null){
                    List<JSONObject> itemList = JSONObject.toJavaObject(object.getJSONArray("itemList"),List.class);
                    for(JSONObject jsonObject:itemList){
                        if(jsonObject.get("imgsList") != null){
                            imgss.addAll(JSONObject.toJavaObject(jsonObject.getJSONArray("imgsList"),List.class));
                        }
                    }
                }
            }
            if(imgss.size() > 0) {
                for(int i1 = 0;i1 < imgss.size();i1++){
                    if(imgss.get(i1).get("url") != null) {
                        files[i1 + x] = new File(fileStorageService.getStrPath(imgss.get(i1).getString("url")));
                    }
                }
            }
        }
        //zip路径
        String zipPash = fileStorageService.getStrPath(files[0].getPath());
        String s = response.get("unitName") != null?response.getString("unitName"):"业务检查";
        zipPash = zipPash.substring(0,zipPash.lastIndexOf(File.separator)) + File.separator + s + ".zip";
        Resource resource = null;
        try {
            //生成zip并获取
            resource = new UrlResource(new File(ZipUtils.zipFiles(files,zipPash,null)).toURI());
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("系统找不到文件路径"));
        }
        if (!resource.exists()) {
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("生成zip失败"));
        }
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            System.out.println("Could not determine file type.");
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        //名字转换
        String[] strArr = resource.getFilename().split("\\.");
        String fileNamePrefix = strArr[0];
        String fileNameSuffix = strArr[1];
        String finalFileName = null;
        try {
            finalFileName = URLEncoder.encode(response.getString("guidanceNum") + "_" + fileNamePrefix,"UTF-8")+"."+fileNameSuffix;
        }catch (UnsupportedEncodingException e){
            System.out.println("文件名字转换异常");
            System.out.println(e.getMessage());
        }
        OperationRepositoryService.saveLog(new SaveLogRequest(
                OperationLog.OperationType.EXPORT,
                "导出业务检查,检查单号:" + response.get("guidanceNum"),
                "业务检查",
                OperationLog.BusinessType.BUSINESS
        ),accountRepositoryService.getById(userId));
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + finalFileName + "\"").body(resource);
    }

    /**
     * 业务检查整份导出 on 2019/11/12 11:02
     *
     * @param id id
     * @param request request
     */
    public ResponseEntity<?> selfOrRepeatBusinessGuidanceWholeExport(Long id,Long userId, HttpServletRequest request){
        Result result = businessInspectService.getById(id);
        if(result.getData() == null){
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在"));
        }
        JSONObject response = JSONObject.parseObject(JSON.toJSONString(result.getData(), SerializerFeature.WriteMapNullValue));
        int i = 1;
        if(response.get("instructorSignImg") != null){
            i += 1;
        }
        if(response.get("unitSignImg") != null){
            i += 1;
        }
        if(response.get("subjects") != null){
            List<JSONObject> list = JSONObject.toJavaObject(response.getJSONArray("subjects"),List.class);
            for(JSONObject object:list){
                if(object.get("imgsList") != null){
                    List imgss = JSONObject.toJavaObject(object.getJSONArray("imgsList"),List.class);
                    if(imgss != null) {
                        i += imgss.size();
                    }
                }
                if(object.get("itemList") != null){
                    List<JSONObject> itemList = JSONObject.toJavaObject(object.getJSONArray("itemList"),List.class);
                    for(JSONObject jsonObject:itemList){
                        if(jsonObject.get("imgsList") != null){
                            List imgs = JSONObject.toJavaObject(jsonObject.getJSONArray("imgsList"),List.class);
                            if(imgs != null) {
                                i += imgs.size();
                            }
                        }
                    }
                }
            }
        }
        File[] files = 	new File[i];
        //pdf
        try {
            files[0] = new File(pdfService.selfOrRepeatCreatePDF(2,id));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("系统找不到文件路径"));
        }
        //文件
        int x = 1;
        if(response.get("instructorSignImg") != null){
            List<JSONObject> object = JSONObject.toJavaObject(response.getJSONArray("instructorSignImg"),List.class);
            if(object != null && object.size() > 0 && object.get(0).get("url") != null) {
                files[1] = new File(object.get(0).getString("url"));
                x += 1;
            }
        }
        if(response.get("unitSignImg") != null){
            List<JSONObject> object = JSONObject.toJavaObject(response.getJSONArray("unitSignImg"),List.class);
            if(object != null && object.size() > 0 && object.get(0).get("url") != null) {
                files[2] = new File(object.get(0).getString("url"));
                x += 1;
            }
        }
        if(response.get("subjects") != null){
            List<JSONObject> list = JSONObject.toJavaObject(response.getJSONArray("subjects"),List.class);
            List<JSONObject> imgss = Lists.newArrayList();
            for(JSONObject object:list){
                if(object.get("imgsList") != null){
                    imgss.addAll(JSONObject.toJavaObject(object.getJSONArray("imgsList"),List.class));
                }
                //选项图片
                if(object.get("itemList") != null){
                    List<JSONObject> itemList = JSONObject.toJavaObject(object.getJSONArray("itemList"),List.class);
                    for(JSONObject jsonObject:itemList){
                        if(jsonObject.get("imgsList") != null){
                            imgss.addAll(JSONObject.toJavaObject(jsonObject.getJSONArray("imgsList"),List.class));
                        }
                    }
                }
            }
            if(imgss.size() > 0) {
                for(int i1 = 0;i1 < imgss.size();i1++){
                    if(imgss.get(i1).get("url") != null) {
                        files[i1 + x] = new File(fileStorageService.getStrPath(imgss.get(i1).getString("url")));
                    }
                }
            }
        }
        //zip路径
        String zipPash = fileStorageService.getStrPath(files[0].getPath());
        String s = response.get("unitName") != null?response.getString("unitName"):"业务检查";
        zipPash = zipPash.substring(0,zipPash.lastIndexOf(File.separator)) + File.separator + s + ".zip";
        Resource resource = null;
        try {
            //生成zip并获取
            resource = new UrlResource(new File(ZipUtils.zipFiles(files,zipPash,null)).toURI());
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("系统找不到文件路径"));
        }
        if (!resource.exists()) {
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("生成zip失败"));
        }
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            System.out.println("Could not determine file type.");
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        //名字转换
        String[] strArr = resource.getFilename().split("\\.");
        String fileNamePrefix = strArr[0];
        String fileNameSuffix = strArr[1];
        String finalFileName = null;
        try {
            finalFileName = URLEncoder.encode(response.getString("guidanceNum") + "_" + fileNamePrefix,"UTF-8")+"."+fileNameSuffix;
        }catch (UnsupportedEncodingException e){
            System.out.println("文件名字转换异常");
            System.out.println(e.getMessage());
        }
        OperationRepositoryService.saveLog(new SaveLogRequest(
                OperationLog.OperationType.EXPORT,
                "导出业务检查,检查单号:" + response.get("guidanceNum"),
                "业务检查",
                OperationLog.BusinessType.BUSINESS
        ),accountRepositoryService.getById(userId));
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + finalFileName + "\"").body(resource);
    }


    /**
     * 业务检查文件导出 on 2019/11/12 11:02
     *
     * @param id id
     * @param request request
     */
    public ResponseEntity<?> businessGuidanceFileExport(Long id,Long userId, HttpServletRequest request){
        Result result = businessInspectService.getById(id);
        if(result.getData() == null){
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在"));
        }
        JSONObject response = JSONObject.parseObject(JSON.toJSONString(result.getData(), SerializerFeature.WriteMapNullValue));
        int i = 0;
        if(response.get("instructorSignImg") != null){
            i += 1;
        }
        if(response.get("unitSignImg") != null){
            i += 1;
        }
        if(response.get("subjects") != null){
            List<JSONObject> list = JSONObject.toJavaObject(response.getJSONArray("subjects"),List.class);
            for(JSONObject object:list){
                if(object.get("imgsList") != null){
                    List imgss = JSONObject.toJavaObject(object.getJSONArray("imgsList"),List.class);
                    if(imgss != null) {
                        i += imgss.size();
                    }
                }
                if(object.get("itemList") != null){
                    List<JSONObject> itemList = JSONObject.toJavaObject(object.getJSONArray("itemList"),List.class);
                    for(JSONObject jsonObject:itemList){
                        if(jsonObject.get("imgsList") != null){
                            List imgs = JSONObject.toJavaObject(jsonObject.getJSONArray("imgsList"),List.class);
                            if(imgs != null) {
                                i += imgs.size();
                            }
                        }
                    }
                }
            }
        }
        File[] files = 	new File[i];
        //文件
        int x = 0;
        if(response.get("instructorSignImg") != null){
            List<JSONObject> object = JSONObject.toJavaObject(response.getJSONArray("instructorSignImg"),List.class);
            if(object != null && object.size() > 0 && object.get(0).get("url") != null) {
                files[0] = new File(object.get(0).getString("url"));
                x += 1;
            }
        }
        if(response.get("unitSignImg") != null){
            List<JSONObject> object = JSONObject.toJavaObject(response.getJSONArray("unitSignImg"),List.class);
            if(object != null && object.size() > 0 && object.get(0).get("url") != null) {
                files[1] = new File(object.get(0).getString("url"));
                x += 1;
            }
        }
        if(response.get("subjects") != null){
            List<JSONObject> list = JSONObject.toJavaObject(response.getJSONArray("subjects"),List.class);
            List<JSONObject> imgss = Lists.newArrayList();
            for(JSONObject object:list){
                if(object.get("imgsList") != null){
                    imgss.addAll(JSONObject.toJavaObject(object.getJSONArray("imgsList"),List.class));
                }
                //选项图片
                if(object.get("itemList") != null){
                    List<JSONObject> itemList = JSONObject.toJavaObject(object.getJSONArray("itemList"),List.class);
                    for(JSONObject jsonObject:itemList){
                        if(jsonObject.get("imgsList") != null){
                            imgss.addAll(JSONObject.toJavaObject(jsonObject.getJSONArray("imgsList"),List.class));
                        }
                    }
                }
            }
            if(imgss.size() > 0) {
                for(int i1 = 0;i1 < imgss.size();i1++){
                    if(imgss.get(i1).get("url") != null) {
                        files[i1 + x] = new File(fileStorageService.getStrPath(imgss.get(i1).getString("url")));
                    }
                }
            }
        }
        //zip路径
        String zipPash = fileStorageService.getStrPath(files[0].getPath());
        String s = response.get("unitName") != null?response.getString("unitName"):"业务检查";
        zipPash = zipPash.substring(0,zipPash.lastIndexOf(File.separator)) + File.separator + s + ".zip";
        Resource resource = null;
        try {
            //生成zip并获取
            resource = new UrlResource(new File(ZipUtils.zipFiles(files,zipPash,null)).toURI());
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("系统找不到文件路径"));
        }
        if (!resource.exists()) {
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("生成zip失败"));
        }
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            System.out.println("Could not determine file type.");
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        //名字转换
        String[] strArr = resource.getFilename().split("\\.");
        String fileNamePrefix = strArr[0];
        String fileNameSuffix = strArr[1];
        String finalFileName = null;
        try {
            finalFileName = URLEncoder.encode(response.getString("guidanceNum") + "_" + fileNamePrefix,"UTF-8")+"."+fileNameSuffix;
        }catch (UnsupportedEncodingException e){
            System.out.println("文件名字转换异常");
            System.out.println(e.getMessage());
        }
        OperationRepositoryService.saveLog(new SaveLogRequest(
                OperationLog.OperationType.EXPORT,
                "导出业务检查,检查单号:" + response.get("guidanceNum"),
                "业务检查",
                OperationLog.BusinessType.BUSINESS
        ),accountRepositoryService.getById(userId));
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + finalFileName + "\"").body(resource);
    }

    /**
     * 指导整改单批量导出 on 2019/11/12 11:08
     *
     * @param request request
     * @param response response
     */
    public void guidanceMendListBatchExport(GuidanceMendListBatchExportRequest request, HttpServletResponse response){
        if(request.getPn() == null){
            request.setPn(1);
        }
        if(request.getPageSize() == null){
            request.setPageSize(30);
        }
        List<GuidanceMendListExcel> mendLists = Lists.newArrayList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mendState",request.getMendState());
        jsonObject.put("guidanceTimeStart",request.getGuidanceTimeStart() != null? DateUtils.dayMinTime(request.getGuidanceTimeStart()):"");
        jsonObject.put("guidanceTimeEnd",request.getGuidanceTimeEnd() != null? DateUtils.dayMaxTime(request.getGuidanceTimeEnd()):"");
        jsonObject.put("keywords",request.getKeywords() != null?request.getKeywords().trim():"");
        PageInfo<JSONObject> pageInfo = guiGuidanceMendListRepositoryService.dataFindPage(request.getPn(),request.getPageSize(),jsonObject);
        if(pageInfo.getList() != null && pageInfo.getList().size() > 0){
            for(JSONObject mendList:pageInfo.getList()){
                GuidanceMendListExcel mendListExcel = new GuidanceMendListExcel();
                mendListExcel.setGuidNum(mendList.get("guidanceNum") != null?mendList.getString("guidanceNum"):"");
                mendListExcel.setTitle(mendList.get("title") != null?mendList.getString("title"):"");
                mendListExcel.setUnit(mendList.get("unit") != null?mendList.getString("unit"):"");
                String mendState = "";
                if(mendList.get("mendState") != null){
                    if(mendList.getInteger("mendState").equals(1)){
                        mendState = "待整改";
                    } else if(mendList.getInteger("mendState").equals(2)){
                        mendState = "待验证";
                    } else if(mendList.getInteger("mendState").equals(3)){
                        mendState = "打回待整改";
                    } else if(mendList.getInteger("mendState").equals(4)){
                        mendState = "验证通过";
                    }
                }
                mendListExcel.setMendState(mendState);
                mendListExcel.setInstructorName(mendList.get("instructorName") != null?mendList.getString("instructorName"):"");
                mendListExcel.setGuideAt(mendList.get("guideAt") != null?mendList.getDate("guideAt"):null);
                mendLists.add(mendListExcel);
            }
            ExcelUtils.generateGuidanceMendListExcelFile(response,mendLists);
            saveLog(OperationLog.OperationType.EXPORT_BATCH, "批量导出指导整改数据");
        }
    }

    /**
     * 指导整改整份导出 on 2019/11/12 11:02
     *
     * @param id id
     * @param request request
     */
    public ResponseEntity<?> guiMendListWholeExport(Long id,Long userId, HttpServletRequest request){
        Result result = guidanceMendListService.getDetails(id);
        if(result.getData() == null){
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在"));
        }
        MendListGetDetailsResult response = (MendListGetDetailsResult)result.getData();
        if(response == null){
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在"));
        }
        int i = 1;
        if(response.getItemList() != null){
            for(MendListItemResult itemResult:response.getItemList()){
                if(itemResult.getImgList() != null){
                    i += itemResult.getImgList().size();
                }
                if(itemResult.getMendListImgList() != null){
                    i += itemResult.getMendListImgList().size();
                }
            }
        }
        File[] files = 	new File[i];
        //pdf
        try {
            files[0] = new File(pdfService.createPDF(3,id));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("系统找不到文件路径"));
        }
        //zip路径
        String zipPash = fileStorageService.getStrPath(files[0].getPath());
        zipPash = zipPash.substring(0,zipPash.lastIndexOf(File.separator)) + File.separator + response.getUnit() + ".zip";
        //文件
        if(response.getItemList() != null){
            List<Imgs> imgss = Lists.newArrayList();
            for(MendListItemResult itemResult:response.getItemList()){
                //条目图片
                if(itemResult.getImgList() != null && itemResult.getImgList().size() > 0){
                    imgss.addAll(itemResult.getImgList());
                }
                //整改图片
                if(itemResult.getMendListImgList() != null && itemResult.getMendListImgList().size() > 0){
                    imgss.addAll(itemResult.getMendListImgList());
                }
            }
            for(int i1 = 0;i1 < imgss.size();i1++){
                files[i1 + 1] = new File(fileStorageService.getStrPath(imgss.get(i1).getUrl()));
            }
        }
        Resource resource = null;
        try {
            //生成zip并获取
            resource = new UrlResource(new File(ZipUtils.zipFiles(files,zipPash,null)).toURI());
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("系统找不到文件路径"));
        }
        if (!resource.exists()) {
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("生成zip失败"));
        }
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            System.out.println("Could not determine file type.");
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        //名字转换
        String[] strArr = resource.getFilename().split("\\.");
        String fileNamePrefix = strArr[0];
        String fileNameSuffix = strArr[1];
        String finalFileName = null;
        try {
            finalFileName = URLEncoder.encode(fileNamePrefix,"UTF-8")+"."+fileNameSuffix;
        }catch (UnsupportedEncodingException e){
            System.out.println("文件名字转换异常");
            System.out.println(e.getMessage());
        }
        OperationRepositoryService.saveLog(new SaveLogRequest(
                OperationLog.OperationType.EXPORT,
                "导出指导整改,指导单号:" + response.getGuidanceNum(),
                "指导整改",
                OperationLog.BusinessType.BUSINESS
        ),accountRepositoryService.getById(userId));
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + finalFileName + "\"").body(resource);
    }

    /**
     * 指导整改文件导出 on 2019/11/12 11:02
     *
     * @param id id
     * @param request request
     */
    public ResponseEntity<?> guiMendListFileExport(Long id,Long userId, HttpServletRequest request){
        Result result = guidanceMendListService.getDetails(id);
        if(result.getData() == null){
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在"));
        }
        MendListGetDetailsResult response = (MendListGetDetailsResult)result.getData();
        if(response == null){
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在"));
        }
        int i = 0;
        if(response.getItemList() != null){
            for(MendListItemResult itemResult:response.getItemList()){
                if(itemResult.getImgList() != null){
                    i += itemResult.getImgList().size();
                }
                if(itemResult.getMendListImgList() != null){
                    i += itemResult.getMendListImgList().size();
                }
            }
        }
        if(i <= 0){
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("没有文件可以下载"));
        }
        File[] files = 	new File[i];
        //文件
        if(response.getItemList() != null){
            List<Imgs> list = Lists.newArrayList();
            for(MendListItemResult itemResult:response.getItemList()){
                if(itemResult.getImgList() != null && itemResult.getImgList().size() > 0){
                    list.addAll(itemResult.getImgList());
                }
                //选项图片
                if(itemResult.getMendListImgList() != null && itemResult.getMendListImgList().size() > 0) {
                    list.addAll(itemResult.getMendListImgList());
                }
            }
            if(list.size() > 0){
                for(int i1 = 0;i1 < list.size();i1++){
                    files[i1] = new File(fileStorageService.getStrPath(list.get(i1).getUrl()));
                }
            }
        }
        //zip路径
        String zipPash = fileStorageService.getStrPath(files[0].getPath());
        zipPash = zipPash.substring(0,zipPash.lastIndexOf(File.separator)) + File.separator + response.getUnit() + ".zip";
        Resource resource = null;
        try {
            //生成zip并获取
            resource = new UrlResource(new File(ZipUtils.zipFiles(files,zipPash,null)).toURI());
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("系统找不到文件路径"));
        }
        if (!resource.exists()) {
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("生成zip失败"));
        }
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            System.out.println("Could not determine file type.");
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        //名字转换
        String[] strArr = resource.getFilename().split("\\.");
        String fileNamePrefix = strArr[0];
        String fileNameSuffix = strArr[1];
        String finalFileName = null;
        try {
            finalFileName = URLEncoder.encode(fileNamePrefix,"UTF-8")+"."+fileNameSuffix;
        }catch (UnsupportedEncodingException e){
            System.out.println("文件名字转换异常");
            System.out.println(e.getMessage());
        }
        OperationRepositoryService.saveLog(new SaveLogRequest(
                OperationLog.OperationType.EXPORT,
                "导出指导整改,指导单号:" + response.getGuidanceNum(),
                "指导整改",
                OperationLog.BusinessType.BUSINESS
        ),accountRepositoryService.getById(userId));
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + finalFileName + "\"").body(resource);
    }

    /**
     * 业务检查批量导出 on 2019/11/13 14:23
     *
     * @param request request
     * @param response response
     */
    public void guidanceBatchExport(GuiBusinessPageRequest request, HttpServletResponse response){
        if(request.getPn() ==  null){
            request.setPn(1);
        }
        if(request.getPageSize() == null){
            request.setPageSize(30);
        }
        Account account = UserPrincipal.getCurrentUser();
        if(account != null && !"ADMIN".equals(account.getRoleName()) && !"管理员".equals(account.getRoleName())
                && !"业务指导处长".equals(account.getRoleName()) && !"正副局长".equals(account.getRoleName())){
            request.setInstructorId(String.valueOf(account.getId()));
        }
        PageInfo<GuiBusinessGuidance> pageInfo = businessGuidanceService.getRepositoryService().findPage(request);
        List<GuiBusinessGuidanceExcel> excelList = Lists.newArrayList();
        if(pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            for(GuiBusinessGuidance guidance :pageInfo.getList()){
                GuiBusinessGuidanceExcel excel = new GuiBusinessGuidanceExcel();
                BeanUtils.copyProperties(guidance,excel);
                if("STAGE".equals(guidance.getState())){
                    excel.setState("暂存");
                }else if("WAIT_CONFIRM".equals(guidance.getState())){
                    excel.setState("待确认");
                }else if("COMPLETE".equals(guidance.getState())){
                    excel.setState("完结");
                }else if("ARCHIVE".equals(guidance.getState())){
                    excel.setState("归档");
                }
                excelList.add(excel);
            }
            ExcelUtils.generateGuidanceBatchExportExcelFile(response, excelList);
        }
    }

    /**
      * 业务指导整份导出 on 2020/9/14 14:18
      *
      * @param id id
      * @param userId userId
      * @param request request
      * @return ResponseEntity<?>
      */
    public ResponseEntity<?> guidanceWholeExport(Long id,Long userId, HttpServletRequest request){
        Result result = businessGuidanceService.getDetails(id);
        if(result.getData() == null){
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在"));
        }
        JSONObject response = JSONObject.parseObject(JSON.toJSONString(result.getData(), SerializerFeature.WriteMapNullValue));
        int i = 1;
        if(response.get("guideAdviceSign") != null){
            i += 1;
        }
        if(response.get("adviceImgSign") != null){
            i += 1;
        }
        if(response.get("itemList") != null){
            List<JSONObject> list = JSONObject.toJavaObject(response.getJSONArray("itemList"),List.class);
            for(JSONObject object:list){
                if(object.get("imgList") != null){
                    List imgss = JSONObject.toJavaObject(object.getJSONArray("imgList"),List.class);
                    if(imgss != null) {
                        i += imgss.size();
                    }
                }
            }
        }
        File[] files = 	new File[i];
        //pdf
        try {
            files[0] = new File(pdfService.createPDF(4,id));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("系统找不到文件路径"));
        }
        //文件
        int x = 1;
        if(response.get("guideAdviceSign") != null && response.getLong("guideAdviceSign") != 0){
            Imgs imgs = imgsService.getById(response.getLong("guideAdviceSign"));
            if(imgs != null) {
                files[1] = new File(imgs.getUrl());
                x += 1;
            }
        }
        if(response.get("adviceImgSign") != null && response.getLong("adviceImgSign") != 0){
            Imgs imgs = imgsService.getById(response.getLong("adviceImgSign"));
            if(imgs != null) {
                files[2] = new File(imgs.getUrl());
                x += 1;
            }
        }
        if(response.get("itemList") != null){
            List<JSONObject> list = JSONObject.toJavaObject(response.getJSONArray("itemList"),List.class);
            List<JSONObject> imgss = Lists.newArrayList();
            for(JSONObject object:list){
                if(object.get("imgList") != null){
                    imgss.addAll(JSONObject.toJavaObject(object.getJSONArray("imgList"),List.class));
                }
            }
            if(imgss.size() > 0) {
                for(int i1 = 0;i1 < imgss.size();i1++){
                    if(imgss.get(i1).get("url") != null) {
                        files[i1 + x] = new File(fileStorageService.getStrPath(imgss.get(i1).getString("url")));
                    }
                }
            }
        }
        //zip路径
        String zipPash = fileStorageService.getStrPath(files[0].getPath());
        String s = response.get("unit") != null?response.getString("unit"):"业务指导";
        zipPash = zipPash.substring(0,zipPash.lastIndexOf(File.separator)) + File.separator + s + ".zip";
        Resource resource = null;
        try {
            //生成zip并获取
            resource = new UrlResource(new File(ZipUtils.zipFiles(files,zipPash,null)).toURI());
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("系统找不到文件路径"));
        }
        if (!resource.exists()) {
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("生成zip失败"));
        }
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            System.out.println("Could not determine file type.");
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        //名字转换
        String[] strArr = resource.getFilename().split("\\.");
        String fileNamePrefix = strArr[0];
        String fileNameSuffix = strArr[1];
        String finalFileName = null;
        try {
            finalFileName = URLEncoder.encode(response.getString("guidanceNum") + "_" + fileNamePrefix,"UTF-8")+"."+fileNameSuffix;
        }catch (UnsupportedEncodingException e){
            System.out.println("文件名字转换异常");
            System.out.println(e.getMessage());
        }
        OperationRepositoryService.saveLog(new SaveLogRequest(
                OperationLog.OperationType.EXPORT,
                "导出业务指导,指导单号:" + response.get("guidanceNum"),
                "业务指导",
                OperationLog.BusinessType.BUSINESS
        ),accountRepositoryService.getById(userId));
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + finalFileName + "\"").body(resource);
    }

    /**
     * 业务指导文件导出 on 2019/11/12 11:02
     *
     * @param id id
     * @param request request
     */
    public ResponseEntity<?> guidanceFileExport(Long id,Long userId, HttpServletRequest request){
        Result result = businessGuidanceService.getDetails(id);
        if(result.getData() == null){
            return ResponseEntity.ok(Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在"));
        }
        JSONObject response = JSONObject.parseObject(JSON.toJSONString(result.getData(), SerializerFeature.WriteMapNullValue));
        int i = 1;
        if(response.get("guideAdviceSign") != null){
            i += 1;
        }
        if(response.get("adviceImgSign") != null){
            i += 1;
        }
        if(response.get("itemList") != null){
            List<JSONObject> list = JSONObject.toJavaObject(response.getJSONArray("itemList"),List.class);
            for(JSONObject object:list){
                if(object.get("imgList") != null){
                    List imgss = JSONObject.toJavaObject(object.getJSONArray("imgList"),List.class);
                    if(imgss != null) {
                        i += imgss.size();
                    }
                }
            }
        }
        File[] files = 	new File[i];
        //文件
        int x = 1;
        if(response.get("guideAdviceSign") != null && response.getLong("guideAdviceSign") != 0){
            Imgs imgs = imgsService.getById(response.getLong("guideAdviceSign"));
            if(imgs != null) {
                files[0] = new File(imgs.getUrl());
                x += 1;
            }
        }
        if(response.get("adviceImgSign") != null && response.getLong("adviceImgSign") != 0){
            Imgs imgs = imgsService.getById(response.getLong("adviceImgSign"));
            if(imgs != null) {
                files[1] = new File(imgs.getUrl());
                x += 1;
            }
        }
        if(response.get("itemList") != null){
            List<JSONObject> list = JSONObject.toJavaObject(response.getJSONArray("itemList"),List.class);
            List<JSONObject> imgss = Lists.newArrayList();
            for(JSONObject object:list){
                if(object.get("imgList") != null){
                    imgss.addAll(JSONObject.toJavaObject(object.getJSONArray("imgList"),List.class));
                }
            }
            if(imgss.size() > 0) {
                for(int i1 = 0;i1 < imgss.size();i1++){
                    if(imgss.get(i1).get("url") != null) {
                        files[i1 + x] = new File(fileStorageService.getStrPath(imgss.get(i1).getString("url")));
                    }
                }
            }
        }
        //zip路径
        String zipPash = fileStorageService.getStrPath(files[0].getPath());
        String s = response.get("unit") != null?response.getString("unit"):"业务指导";
        zipPash = zipPash.substring(0,zipPash.lastIndexOf(File.separator)) + File.separator + s + ".zip";
        Resource resource = null;
        try {
            //生成zip并获取
            resource = new UrlResource(new File(ZipUtils.zipFiles(files,zipPash,null)).toURI());
        }catch (Exception e){
            e.printStackTrace();
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("系统找不到文件路径"));
        }
        if (!resource.exists()) {
            return ResponseEntity.ok(Result.body(id, ResultType.BUSINESS_ERROR).withMessage("生成zip失败"));
        }
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            System.out.println("Could not determine file type.");
        }
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        //名字转换
        String[] strArr = resource.getFilename().split("\\.");
        String fileNamePrefix = strArr[0];
        String fileNameSuffix = strArr[1];
        String finalFileName = null;
        try {
            finalFileName = URLEncoder.encode(response.getString("guidanceNum") + "_" + fileNamePrefix,"UTF-8")+"."+fileNameSuffix;
        }catch (UnsupportedEncodingException e){
            System.out.println("文件名字转换异常");
            System.out.println(e.getMessage());
        }
        OperationRepositoryService.saveLog(new SaveLogRequest(
                OperationLog.OperationType.EXPORT,
                "导出业务指导,指导单号:" + response.get("guidanceNum"),
                "业务指导",
                OperationLog.BusinessType.BUSINESS
        ),accountRepositoryService.getById(userId));
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + finalFileName + "\"").body(resource);
    }

    /**
     * 新增日志 on 2019/11/14 10:37
     *
     * @param operationType 操作类型
     * @param description   描述
     */
    private void saveLog(OperationLog.OperationType operationType, String description) {
        OperationRepositoryService.saveLog(new SaveLogRequest(
                operationType,
                description,
                "指导整改",
                OperationLog.BusinessType.BUSINESS
        ));
    }
}